package com.learn.springboot.service.impl;

import com.learn.springboot.pojo.Cat;
import com.learn.springboot.service.CatService;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author dyz
 * @program learning
 * @create 2019-08-12 16:55
 */
@Service
public class CatServiceImpl implements CatService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public void save(String catName, Integer catAge) {
        jdbcTemplate.update("INSERT INTO cat(cat_name, cat_age) VALUES (?,?)", catName, catAge);
    }

    @Override
    public void deleteById(Integer id) {
        jdbcTemplate.update("DELETE FROM cat WHERE id = ?", id);
    }

    @Override
    public void update(Integer id, String catName, Integer catAge) {
        jdbcTemplate.update("UPDATE cat SET cat_name = ? , cat_age = ?  WHERE id = ?", catName, catAge, id);
    }

    @Override
    public List<Cat> getAll() {
        List<Cat> list = new ArrayList<Cat>();

        jdbcTemplate.query("select * from cat", rs -> {
            Cat cat = new Cat();
            cat.setId(rs.getInt("id"));
            cat.setCatName(rs.getString("cat_name"));
            cat.setCatAge(rs.getInt("cat_age"));
            list.add(cat);
        });

        return list;
    }
}
